//
//  GFScanViewController.m
//  GoFactory
//
//  Created by wtb on 2017/12/19.
//  Copyright © 2017年 KQZK. All rights reserved.
//

#import "GFScanViewController.h"
#import "GFScanView.h"
#import "WMZDialog.h"
#import "KqScreenUtil.h"
#import "KqTool.h"
#import "GFScan.h"
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>

typedef NS_ENUM(NSInteger,ScanDevice) {
    ScanAnyDevice,
    ScanBoxDevice
};
@interface GFScanViewController ()
<
UIImagePickerControllerDelegate,
UINavigationControllerDelegate
>
{
    CGFloat _widthScan;
    NSInteger _num;
    BOOL _down;
    NSTimer *_timer;
    CAShapeLayer *_shapeLayer;
}
@property(nonatomic,strong) UIView *lineScan;
@property(nonatomic,strong) GFScan *scan;
@property(nonatomic,assign) ScanDevice scanDevice;
@property(nonatomic,assign) BOOL isQr;
@end

@implementation GFScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configViewRect];
    [self configNavBar];
    [self createScan];
    [self registerNofication];
}

-(void)registerNofication
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
}

-(void)applicationBecomeActive
{
    [self.scan setupCamera];
}

-(void)applicationEnterBackground
{
    [self.scan stop];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.scan stop];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.scan stop];
    [_timer invalidate];
    _timer = nil;
}

-(void)configViewRect
{
    
    _widthScan = RateHeight(270);
    
    _shapeLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, CGRectMake((ScreenWidth()-_widthScan)/2,[self getScanTopPosition],_widthScan,_widthScan));
    CGPathAddRect(path, nil, self.view.bounds);

    [_shapeLayer setFillRule:kCAFillRuleEvenOdd];
    [_shapeLayer setPath:path];
    [_shapeLayer setFillColor:[UIColor blackColor].CGColor];
    [_shapeLayer setOpacity:0.5];
    [_shapeLayer setNeedsDisplay];
    [self.view.layer addSublayer:_shapeLayer];
}

-(void)configNavBar
{
    [[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
    if (![KqTool getNav]) {
        
        UIView *navbgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth(), 44+StatusBarHeight())];
        navbgView.backgroundColor = self.navColor?self.navColor:[UIColor colorWithRed:58/255.0 green:85/255.0 blue:155/255.0 alpha:1];
        [self.view addSubview:navbgView];
        
        UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, StatusBarHeight(), ScreenWidth(), 44)];
        [navbgView addSubview:nav];
        
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setImage:[KqTool tz_imageNamedFromMyBundle:@"return2"] forState:UIControlStateNormal];
        backBtn.frame = CGRectMake(0, 0, 44, 44);
        [nav addSubview:backBtn];
        [backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, ScreenWidth()-88, 44)];
        titleLabel.numberOfLines = 1;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = self.title?self.title:@"扫码";
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.font = [UIFont systemFontOfSize:16];
        [nav addSubview:titleLabel];
        
        if(!self.notSupportAlbum){
            UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            rightNavBtn.frame = CGRectMake(ScreenWidth()-44, 0, 44, 44);
            [rightNavBtn setImage:[KqTool tz_imageNamedFromMyBundle:@"ic_photo_20_white"] forState:UIControlStateNormal];
            
            [rightNavBtn addTarget:self action:@selector(goAlbum)
                  forControlEvents:UIControlEventTouchUpInside];
            [nav addSubview:rightNavBtn];
        }
        return;
    }else{
        if(self.navigationItem){
            UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[KqTool tz_imageNamedFromMyBundle:@"return2"] style:UIBarButtonItemStyleDone target:self action:@selector(goBack)];
            self.navigationItem.leftBarButtonItem = left;
        }
    }
    if (!self.title) {
        self.title = @"扫码";
    }
    
    if (!self.notSupportAlbum) {
        UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightNavBtn setImage:[KqTool tz_imageNamedFromMyBundle:@"ic_photo_20_white"] forState:UIControlStateNormal];
        
        if(self.navigationItem){
            UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:rightNavBtn];
            self.navigationItem.rightBarButtonItem = item;
        }
        
        [rightNavBtn addTarget:self action:@selector(goAlbum)
              forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void)goBack{
    if (self.backBlock) {
        self.backBlock();
    }
    [self pop];
}

-(void)pop{
    if([KqTool getNav]){
        if (self.isBackHome) {
            self.tabBarController.selectedIndex = 0;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)goAlbum
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.view.backgroundColor = [UIColor whiteColor];
    picker.modalPresentationStyle = UIModalPresentationCurrentContext;
    picker.allowsEditing = NO;
    /**
     * 相册呈现的样式
     * UIImagePickerControllerSourceTypeCamera          调取摄像头
     * UIImagePickerControllerSourceTypePhotoLibrary    直接全部呈现系统相册
     * UIImagePickerControllerSourceTypeSavedPhotosAlbum图库
     */
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

-(CGFloat)getScanTopPosition{
    CGFloat statutsBarHeight = 0;
    if (@available(iOS 13.0, *)) {
      UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager;
        statutsBarHeight = statusBarManager.statusBarFrame.size.height;
    }else {
        statutsBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    }
    
    CGFloat top = (ScreenHight()-statutsBarHeight-44-_widthScan)/2;
    return top;
}

-(void)createScan
{
    __weak __typeof(self)GF = self;
    
    
    
    CGFloat top = [self getScanTopPosition];
    
    UIImageView *scanImage = [[UIImageView alloc] init];
    scanImage.image = [KqTool tz_imageNamedFromMyBundle:@"scanwindow"];
    scanImage.frame = CGRectMake((ScreenWidth()-_widthScan)/2.0, top, _widthScan, _widthScan);
    [self.view addSubview:scanImage];
    
    _down = NO;
    _num = 0;
    
    self.lineScan = [[UIView alloc] init];
    self.lineScan.frame = CGRectMake((ScreenWidth()-_widthScan*0.8)/2,top+10,
                                     _widthScan*0.8, 2);
    self.lineScan.backgroundColor = [UIColor colorWithRed:58/255.0 green:85/255.0 blue:155/255.0 alpha:1];
    [self.view addSubview:self.lineScan];
    
//    UILabel *node = [ToolKit createLabelWithText:Localized(@"scanNode", @"Public") textColor:GFColor(@"#ffffff") font:[UIFont gfFontSizeWithFloat:16] textAlignment:NSTextAlignmentCenter];
    UILabel *node = [[UILabel alloc] init];
    node.text = self.note?self.note:@"请将方框对准二维码/条码开始扫描";
    node.textColor = [UIColor whiteColor];
    node.font = [UIFont systemFontOfSize:16];
    node.textAlignment = NSTextAlignmentCenter;
    node.numberOfLines = 3;
    node.frame = CGRectMake(0, CGRectGetMaxY(scanImage.frame)+15, ScreenWidth(), 40);
    [self.view addSubview:node];
    
    self.scan = [[GFScan alloc] initWithPreView:self.view isSupportBarcode:!self.notSupportBarcode success:^(NSString *value, NSString *type) {
//        [_timer setFireDate:[NSDate distantFuture]];
                
        if (GF.result) {
            [GF pop];
//            [GF.navigationController popViewControllerAnimated:YES];
            GF.result(value,type);
        }
                
        //        if (GF.scanDevice == ScanAnyDevice) {
        //            //调转到网页
        //            [GF scanCallback:scanStr];
        //        }else{
        //            //扫box结果
        //            [GF scanCallback:scanStr];
        //            if (GF.result) {
        //                GF.result(scanStr);
        //                [GF.navigationController popViewControllerAnimated:YES];
        //            }
        //        }
    }];
    [self.scan start];
    if (@available(iOS 10.0, *)) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:.02 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [GF animationScan];
        }];
    } else {
        _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:GF selector:@selector(animationScan) userInfo:nil repeats:YES];
        // Fallback on earlier versions
    }
}

-(void)animationScan
{
    if (_down == NO) {
        _num ++;
        self.lineScan.frame = CGRectMake((ScreenWidth() - _widthScan*0.8)/2,
                                         [self getScanTopPosition]+10 + 2*_num,
                                         _widthScan*0.8,
                                         2);
        if (2*_num >= RateHeight(270) - 20) {
            _down = YES;
        }
    }else{
        _num --;
        self.lineScan.frame = CGRectMake((ScreenWidth() - _widthScan*0.8)/2,
                                         [self getScanTopPosition]+10 + 2*_num,
                                         _widthScan*0.8,
                                         2);
        if (2 * _num <= 0) {
            _down = NO;
            _num = 0;
        }
    }
//    if(!self.notSupportBarcode){
//        if(_num%6 == 0){
//            _isQr = !self.isQr;
//            [self.scan changeScanMetaTypes:self.isQr];
//        }
//    }
}

//#pragma mark GFScanViewDelegate
//-(void)clickAnyScan
//{
//    self.scanDevice = ScanAnyDevice;
//}
//
//-(void)clickBoxScan
//{
//    self.scanDevice = ScanBoxDevice;
//}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image.size.width > 280 && image.size.height > 280) {
        if (image.size.width > image.size.height) {
            CGSize size = CGSizeMake(280, 280*image.size.height/image.size.width);
            UIGraphicsBeginImageContext(size);
            [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }else{
            CGSize size = CGSizeMake(280*image.size.width/image.size.height, 280);
            UIGraphicsBeginImageContext(size);
            [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        [GFScan recognizeImage:image success:^(NSArray *result) {
            if (result.count > 0) {
                NSString *resultStr = result.firstObject;
                [self scanCallback:resultStr];
            }
        }];
    }];
}

-(void)scanCallback:(NSString *)result
{
    __weak __typeof(self)GF = self;
    if ([result hasPrefix:@"http://"] || [result hasPrefix:@"https://"]) {
        NSURL *url = [NSURL URLWithString:result];
        if (url) {
            [GF.navigationController popViewControllerAnimated:YES];
            if (@available(iOS 10.0, *)){
                [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionsSourceApplicationKey : @YES} completionHandler:nil];
            }else{
                [[UIApplication sharedApplication] openURL:url];
            }
        }else{
            [GF.navigationController popViewControllerAnimated:YES];
            Dialog()
                .wTypeSet(DialogTypeAuto)
                .wMessageSet(@"无效链接")
                .wStart();
        }
    }else if (GF.result && result.length > 0) {
        [GF.navigationController popViewControllerAnimated:YES];
        GF.result(result,@"QRCode");
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
